package org.tinygame.herostory.handler;

import io.netty.channel.ChannelHandlerContext;
import org.tinygame.herostory.mode.MoveState;
import org.tinygame.herostory.mode.User;
import org.tinygame.herostory.mode.UserManager;
import org.tinygame.herostory.msg.GameMsgProtocol;

public class WhoElseIsHereCmdHandler implements ICmdHandler<GameMsgProtocol.WhoElseIsHereCmd> {

    /**
     * 处理同时在线 - 显示所有人 - 感知其他英雄
     * @param ctx
     * @param msg
     */
    @Override
    public void handler(ChannelHandlerContext ctx, GameMsgProtocol.WhoElseIsHereCmd msg) {
        GameMsgProtocol.WhoElseIsHereResult.Builder resultBuilder = GameMsgProtocol.WhoElseIsHereResult.newBuilder();
        for (User user : UserManager.getUsers()) {

            if(null == user){
                continue;
            }
            GameMsgProtocol.WhoElseIsHereResult.UserInfo.Builder userInfoBuilder = GameMsgProtocol.WhoElseIsHereResult.UserInfo.newBuilder();
            userInfoBuilder.setUserId(user.getUserId());
            userInfoBuilder.setHeroAvatar(user.getHeroAvatar());

            //获取移动状态 - 这里是记录英雄的位置
            MoveState moveState = null;
            if(user.getMoveState() == null){
                moveState = new MoveState();
                user.setMoveState(moveState);
            } else {
                moveState = user.getMoveState();
            }

            GameMsgProtocol.WhoElseIsHereResult.UserInfo.MoveState.Builder msBuilder = GameMsgProtocol.WhoElseIsHereResult.UserInfo.MoveState.newBuilder();
            msBuilder.setFromPosX(moveState.getFromPosX());
            msBuilder.setFromPosY(moveState.getFromPosY());
            msBuilder.setToPosX(moveState.getToPosX());
            msBuilder.setToPosY(moveState.getToPosY());
            msBuilder.setStartTime(moveState.getStartTime());

            //将移动状态设置到用户信息
            userInfoBuilder.setMoveState(msBuilder);

            resultBuilder.addUserInfo(userInfoBuilder);
        }

        GameMsgProtocol.WhoElseIsHereResult newResult = resultBuilder.build();
        ctx.writeAndFlush(newResult);
    }
}
